package bma.common.netty.tester;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelDownstreamHandler;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.DownstreamMessageEvent;
import org.jboss.netty.channel.MessageEvent;

import bma.common.netty.handler.ChannelHandlerContextWrap;

public class ChannelHandlerEncoderTester implements ChannelDownstreamHandler {

	private ChannelDownstreamHandler encoder;

	public ChannelHandlerEncoderTester() {
		super();
	}

	public ChannelHandlerEncoderTester(ChannelDownstreamHandler encoder) {
		super();
		this.encoder = encoder;
	}

	public ChannelDownstreamHandler getEncoder() {
		return encoder;
	}

	public void setEncoder(ChannelDownstreamHandler encoder) {
		this.encoder = encoder;
	}

	@Override
	public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		if (e instanceof MessageEvent) {
			MessageEvent msg = (MessageEvent) e;
			messageReceived(ctx, msg);
		}
		ctx.sendDownstream(e);
	}

	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {

		Object m = e.getMessage();
		if (m instanceof ChannelBuffer) {
			ctx.sendDownstream(e);
			return;
		}

		ChannelHandlerContextWrap newContext = new ChannelHandlerContextWrap(
				ctx) {

			@Override
			public void sendDownstream(ChannelEvent e) {
				// do nothing
				encodeObject(e);
			}

		};
		encoder.handleDownstream(
				newContext,
				new DownstreamMessageEvent(e.getChannel(), e.getFuture(), m, e
						.getRemoteAddress()));
	}

	public void encodeObject(ChannelEvent e) {

	}
}
